/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.teacake.filteringproxy;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Formatter;
import java.io.ByteArrayOutputStream;
/**
 *
 * @author tkleisas
 */
public class HttpChannel extends Thread {
    public HttpChannel(Socket socket, Logfile logfile)
    {
        this.m_socket = socket;
        this.m_logfile = logfile;


        

    }
    public void run()
    {
        boolean finished=false;
        log("connection request from " +m_socket.getInetAddress().toString());
        try
        {
            this.m_is = m_socket.getInputStream();
            this.m_os = m_socket.getOutputStream();
        }
        catch(Exception e)
        {
            return;
        }
        while(!finished)
        {
            try
            {
                m_readbuffer = null;
                int c=0;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while((c=m_is.read())!=-1)
                {
                    baos.write(c);
                }
                m_readbuffer = baos.toByteArray();
                try
                {
                    m_header = new HttpHeader(m_readbuffer);
                    String header = m_header.getFirstLine();

                    log(" REQUEST: "+header);
                    log(" REQUEST HEADER INFO\r\n"+m_header.printHeaders());
                    String url = header.substring(header.indexOf(" "), header.lastIndexOf(" "));
                    String hostname = URLProcessor.extractHostname(url);
                    int port = URLProcessor.extractPort(url);
                    m_httpclient = new HttpClient();
                    m_httpclient.connect(hostname, port);

                    byte[] response = m_httpclient.doRequest(m_readbuffer, 5000);
                    try
                    {
                        HttpHeader  responseHeader = new HttpHeader(response);
                        log(" RESPONSE HEADER INFO\r\n"+responseHeader.printHeaders());
                        if(responseHeader.getValue("Content-Type:").indexOf("text/html")>=0)
                        {
                            String textinfo = responseHeader.getValue("Content-Type:");
                            int i = textinfo.indexOf("charset");
                            int len = "charset".length();
                            if(i>=0)
                            {
                                String charset = textinfo.substring(i+len);
                                response = HttpResponseFilter.filterResponse(response, url, charset);
                            }
                            log("RESPONSE \r\n"+new String(response));
                        }

                    }
                    catch(Exception pex)
                    {

                    }
                    m_os.write(response);
                    m_os.flush();



                }
                catch(Exception e)
                {
                    m_header = null;
                    finished = true;
                }
            }
            catch(Exception e)
            {
                finished = true;
            }

        }
        try
        {
            m_os.close();
            m_is.close();
            m_running = false;
            m_socket.close();
        }
        catch(Exception e)
        {
            this.log("Error:"+e.getMessage());
        }
    }
    public synchronized void  log(String message)
    {
       if(m_logfile==null)
       {
           return;
       }
       Formatter formatter = new Formatter();
       System.out.println(message);
       m_logfile.write( formatter.format("%1$tY/%1$tm/%1$td %1$tH:%1$tM:%1$tS.%1$tL ",java.util.Calendar.getInstance())+message+"\r\n");
    }
    private Formatter m_formatter;
    private Socket m_socket;
    private InputStream m_is;
    private OutputStream m_os;
    private boolean m_running;
    private byte[] m_readbuffer;
    private HttpClient m_httpclient;
    private HttpHeader m_header;
    private Logfile m_logfile;
}
